package com.jn.erp.security.filter;

import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.security.entity.LoginUser;
import com.jn.erp.security.service.TokenService;
import com.jn.erp.security.utils.WxsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 接口过滤 验证只有家长端能访问的接口
 *
 * @author jn
 */
@Component
public class StudentOnlyFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final List<String> whiteList = Arrays.asList(
            "/smp/login",
            "/smp/bind",
            "/smp/studentInfos",
            "/wxs/**",
            "/wxauth/**",
            "/wxmp/**"
    );

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            Set<String> permissions = loginUser.getPermissions();
            boolean isStudnet = permissions.contains(WxsUtils.WXS_PERMISSIONS);
            String requestURI = request.getRequestURI();
            //员工禁止访问家长接口
            if (!isStudnet && !antPathMatcher.match("/wxs/**", requestURI)) {
                chain.doFilter(request, response);
            }
            //家长
            if (isStudnet) {
                // 访问/wxs开头的请求 需要家长身份 或者有额外开放的白名单
                if(isWhiteListed(requestURI)){
                    chain.doFilter(request, response);
                }else{
                    System.out.println(requestURI);
                    throw new ServletException("权限不足!");
                }
            }
        } else {
            //只针对有登录后的用户做操作
            chain.doFilter(request, response);
        }

    }

    public boolean isWhiteListed(String path) {
        return whiteList.stream().anyMatch(item -> antPathMatcher.match(item, path));
    }
}
